package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.ExtentGroupLogic;
import cn.topevery.garden.dal.logic.ExtentLogic;
import cn.topevery.garden.dal.logic.ExtentPartsLogic;
import cn.topevery.garden.dal.logic.ParkLogic;
import cn.topevery.garden.entity.impot.ExtentImportParam;
import cn.topevery.garden.entity.po.Extent;
import cn.topevery.garden.entity.po.ExtentParts;
import cn.topevery.garden.entity.query.ExtentQuery;
import cn.topevery.garden.entity.vo.ExtentVO;
import cn.topevery.garden.wapi.utils.ExcelUtils;
import hw.topevery.basis.dal.logic.SysDictLogic;
import hw.topevery.basis.entity.fetch.DictFetch;
import hw.topevery.basis.entity.po.SysDict;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.GeometryHelper;
import hw.topevery.framework.Utility;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.enums.GeometryTypeEnum;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 片区管理
 *
 * @author code -generate
 * @created 2021 -08-23 13:55:33
 * @date 2021 -08-06
 */
@Api(tags = "片区管理接口")
@RestController
@RequestMapping("/extent")
public class ExtentController extends BaseController {


    /**
     * The Extent logic.
     */
    @Autowired
    ExtentLogic extentLogic;

    @Autowired
    ExtentPartsLogic extentPartsLogic;

    @Autowired
    ExtentGroupLogic extentGroupLogic;

    @Autowired
    ParkLogic parkLogic;

    @Autowired
    SysDictLogic sysDictLogic;

    /**
     * 获取分页列表
     *
     * @param query the query
     * @return json result
     * @author wenzhao.lin
     * @created 2021 -08-23 13:55:33 List page json result.
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<Extent>> listPage(@RequestBody ExtentQuery query) {
        DataPager<Extent> dataPager = extentLogic.listPage(query);
        return JsonResult.ok(dataPager);
    }

    @PostMapping("/options")
    public JsonResult options(@RequestBody ExtentQuery query) {
        return JsonResult.ok(extentLogic.options(query));
    }

    /**
     * 描述 新增/编辑 信息.
     *
     * @param dto the dto
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-23 13:55:33 Save or update json result.
     */
    @ApiOperation("新增/编辑 信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(@Valid @RequestBody Extent dto) {
        if (dto.getId() == null) {
            dto.setEntityId(Utility.uuidRandomString());
            dto.setDbStatus(false);
        }
        if (dto.mapRangesPoints != null && dto.mapRangesPoints.size() > 0) {
            dto.geomBd09 = GeometryHelper.getGeometry(GeometryHelper.ListtoWellKnownText(dto.mapRangesPoints, GeometryTypeEnum.PLANE));
            dto.geomMkt = GeometryHelper.getGeometry(GeometryHelper.MectorListtoWellKnownText(dto.mapRangesPoints, GeometryTypeEnum.PLANE));
        }

        Integer userId = getUser().id;
        boolean isSave = extentLogic.saveOrUpdate(userId.toString(), dto);
        if (isSave) {
            // 保存部件
            extentPartsLogic.saveOrUpdate(userId.toString(), dto.getId(), dto.getPartsList());

            // 保存群组
            extentGroupLogic.saveOrUpdate(userId.toString(), dto.getId(), dto.getGroupList());

            return JsonResult.ok(true);
        } else {
            return JsonResult.error("保存失败");
        }
    }


    /**
     * 描述 通过id获取详情
     *
     * @param id the id
     * @return the by id
     * @author wenzhao.lin
     * @created 2021 -08-25 10:53:27
     */
    @GetMapping(value = "/getById")
    @ApiOperation(value = "通过id获取详情")
    public JsonResult<?> getById(Integer id) {
        if (id == null) {
            return JsonResult.error("id不能为空");
        }
        Extent extent = extentLogic.getById(id);
        if (extent.geomBd09 != null) {
            extent.mapRangesPoints = GeometryHelper.getGeometryPoint(extent.geomBd09);
            extent.geomBd09 = null;
        }

        // 部件
        List<ExtentParts> parts = extentPartsLogic.getListById(extent.id);
        extent.setPartsList(parts);

        return JsonResult.ok(extent);
    }


    /**
     * 描述 根据自增ID批量删除.
     *
     * @param ids the ids
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-23 13:55:33 Delete batch by id json result.
     */
    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        extentLogic.deleteBatchById(getUser().id.toString(), ids);
        return JsonResult.ok(true);
    }

    /**
     * 描述 导出信息.
     *
     * @param query    the query
     * @param response the response
     * @author wenzhao.lin
     * @created 2021 -08-23 13:55:33 Export.
     */
    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(ExtentQuery query, HttpServletResponse response) {
        List<Extent> list = extentLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", Extent.class, "", response);
    }


    /**
     * 描述 检查导入数据.
     *
     * @param file the file
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:59 Analysis excel data json result.
     */
    @PostMapping("/analysisExcel")
    public JsonResult AnalysisExcelData(@RequestParam("file") MultipartFile file) {
        boolean isPass = true;
        String msg = "";
        List<ExtentVO> dataList = null;
        try {
            dataList = ExcelUtils.importExcel(file, 0, 1, ExtentVO.class);
        } catch (Exception e) {
            msg = "解析发生错误，请按照模板格式填写数据！";
            return JsonResult.error(msg);
        }

        List<ExtentVO> newData = new ArrayList<>();
        for (ExtentVO p : dataList) {
            String anaylsisRes = "";
            if (p.getSid() == 0 && p.getName() == null) {
                break;
            }
            boolean isExists1 = extentLogic.isExit("c_name", p.getName());
            if (isExists1) {
                anaylsisRes += "片区名称与现有重复；";
            }
            boolean isExists2 = extentLogic.isExit("c_code", p.getCode());
            if (isExists2) {
                anaylsisRes += "片区编码与现有重复；";
            }

            if (anaylsisRes.length() > 0) {
                p.setPass(false);
                p.setAnalysisRes(anaylsisRes);
            } else {
                p.setPass(true);
                p.setAnalysisRes("验证通过");
            }
            newData.add(p);
        }
        isPass = !newData.stream().anyMatch(a -> a.isPass() == false);
        Map<String, Object> res = new HashMap<>();
        res.put("isPass", isPass);
        res.put("data", newData);
        return JsonResult.ok(res);
    }

    /**
     * 描述 导入数据.
     *
     * @param param the param
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:53 Import excel data json result.
     */
    @PostMapping("/importExcel")
    public JsonResult importExcelData(@RequestBody ExtentImportParam param) {

        SysUser user = getUser();
        if (param.getTableData() != null && param.getTableData().size() > 0) {

            for (ExtentVO p : param.getTableData()) {
                Extent tmp = new Extent();
                Integer parkId = parkLogic.getParkIdByCodeAndName(p.getParkCode(), p.getParkName());

                tmp.setName(p.getName());
                tmp.setParkId(parkId);
                tmp.setParkName(p.getParkName());
                tmp.setCode(p.getCode());
                tmp.setAddress(p.getAddress());
                tmp.setArea(p.getArea());
                tmp.setTypeName(p.getTypeName());
                tmp.setLinkUserId(p.getLinkUserId());
                tmp.setLinkUserName(p.getLinkUserName());
                tmp.setLinkPhone(p.getLinkPhone());
                tmp.setRemark(p.getRemark());

                extentLogic.saveOrUpdate(user.id.toString(), tmp);
            }
        } else {
            return JsonResult.error("导入数据列表不能为空");
        }
        return JsonResult.ok();
    }

    @ApiOperation("根据类别的命名空间Id及名称获取列表")
    @PostMapping("/getCheckTypeList")
    public JsonResult<?> getCheckTypeList(@RequestBody DictFetch para) {
        List<SysDict> list = sysDictLogic.getListDict(para);
        return JsonResult.ok(list);
    }

    @ApiOperation("根据坐标查找片区")
    @GetMapping("getExtentsByLngLat")
    public JsonResult getExtentsByLngLat(double lng, double lat) {
        List<Extent> extentsByLngLat = extentLogic.getExtentsByLngLat(lng, lat, 0);
        return JsonResult.ok(extentsByLngLat);
    }
}
